<?php

declare(strict_types=1);

namespace App\Services;

use EasyWeChat\Factory;

class WechatService
{
    /**
     * @param string $code
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public static function getMiniProgramSession(string $code): array
    {
        $config = config('wechat.mini_program.default');
        $mini   = Factory::miniProgram($config);

        return $mini->auth->session($code);
    }

    /**
     * 获取accesstoken
     *
     * @throws \Exception
     */
    public static function getAccessToken(string $appid, string $secret): string
    {
        $url  = sprintf('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s', $appid, $secret);
        $resp = HttpService::curlGet($url);
        $data = json_decode($resp, true);
        if (!isset($data['access_token'])) {
            throw new \Exception('获取token异常 err ' . $resp);
        }

        return $data['access_token'];
    }

    /**
     * 生成参数二维码
     * @param string $fname
     * @param $scene
     * @param string $path
     * @param int $width
     * @return string
     */
    public static function createMiniQr(string $fname, $scene, string $path = 'pages/index/index', int $width = 280): string
    {
        $appid = env('WECHAT_MINI_PROGRAM_APPID');
        $secret = env('WECHAT_MINI_PROGRAM_SECRET');
        try {
            $token = self::getAccessToken($appid, $secret);
        } catch (\Throwable $e) {
            logException($e);
            return '';
        }
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $token;
        $post = [
            'scene' => $scene,
            'width' => $width,
            'page' => $path,
        ];
        $buffer = HttpService::curlPost($url, $post);
        $filename = storage_path('download/' . $fname);
        file_put_contents($filename, $buffer);
        return $filename;
    }
}
